﻿using System;
using System.Collections.Generic;
using System.IO;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Directory = Lucene.Net.Store.Directory;

namespace Ledict.ConditionExtract.BLL
{
    public class LdIndexReader
    {
        private static LdIndexReader _LdIndexReader;
        private readonly IDictionary<string, Directory> _DictDirectory;
        private readonly IDictionary<string, IndexReader> _DictIndexReader;
        private readonly IDictionary<string, DateTime> _DictIndexTime;

        private LdIndexReader()
        {
            if (_DictIndexReader == null)
            {
                _DictIndexReader = new Dictionary<string, IndexReader>();
                _DictDirectory = new Dictionary<string, Directory>();
                _DictIndexTime = new Dictionary<string, DateTime>();
            }
        }

        private void DirectoryInit(string index)
        {
            var directory = FSDirectory.Open(index);
            _DictDirectory.Add(index, directory);
        }

        public Directory GetDirectory(string index)
        {
            if (!_DictDirectory.ContainsKey(index))
            {
                DirectoryInit(index);
            }
            return _DictDirectory[index];
        }

        public IndexReader GetIndexReader(string index)
        {
            if (!_DictIndexReader.ContainsKey(index))
            {
                IndexReadInit(index);
            }
            else
            {
                var dicInfo = new DirectoryInfo(index);

                var newTime = dicInfo.LastWriteTime; //索引获取最新修改时间
                var oldTime = _DictIndexTime[index]; //上次时间
                var span1 = newTime - oldTime;
                var difference = span1.Hours;
                // int difference = span1.Minutes ; //只会获取分，2小时10分得到结果10

                if (difference >= 1) //判断是否重新打开索引reader
                {
                    IndexReadAppend(index);
                }
            }

            return _DictIndexReader[index];
        }

        public static LdIndexReader GetInstance()
        {
            if (_LdIndexReader == null)
            {
                _LdIndexReader = new LdIndexReader();
            }
            return _LdIndexReader;
        }

        private void IndexReadInit(string index)
        {
            var reader = IndexReader.Open(FSDirectory.Open(index), true);
            _DictIndexReader.Add(index, reader);

            var dicInfo = new DirectoryInfo(index);

            var newTime = dicInfo.LastWriteTime; //索引获取最新修改时间
            _DictIndexTime.Add(index, newTime);
        }


        private void IndexReadAppend(string index)
        {
            var reader = IndexReader.Open(FSDirectory.Open(index), true);
            _DictIndexReader[index] = reader;

            var dicInfo = new DirectoryInfo(index);

            var newTime = dicInfo.LastWriteTime; //索引获取最新修改时间
            _DictIndexTime[index] = newTime;
        }
    }
}